package vlt.el.main;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import vlt.el.db.DBConnection;
import vlt.el.db.SQLGenerator;
import vlt.el.db.dao.VltDAO;
import vlt.el.util.Config;

public class IncrementalLoad {

	public static void main(String[] args) throws FileNotFoundException, IOException, SQLException, ClassNotFoundException {
		DBConnection db = new DBConnection();
		db.connectOrig(true);
		db.connectDest(true);

		try{
			Config config = Config.getInstance();
			config.reloadConfigProperties();
			db.connectOrig(true);
			SQLGenerator sqlGenerator = new SQLGenerator();
			
			String ctlOwner = config.getConfigProperty("database.orig.ctl_owner");
			String ctlTable = config.getConfigProperty("database.orig.ctl_table");

			String owner = config.getConfigProperty("database.orig.owner");
			String table = config.getConfigProperty("database.orig.table");
			
			String ownerDest = config.getConfigProperty("database.dest.owner");
			String tableDest = config.getConfigProperty("database.dest.table");

			
			Map<String, String> columns = sqlGenerator.listTableColumns(
					owner,
					table,
					db.getConnOrig());
			
			String insertDest = sqlGenerator.generateInsert(
					ownerDest,
					tableDest, columns);
			
	    	List<String> pk = sqlGenerator.getPK(ownerDest, tableDest, db.getConnDest());

			String deleteDest = sqlGenerator.generateDelete(
					ownerDest,
					tableDest, 
					pk,
					db.getConnDest());
			
			int rowsBeforeCommit = Integer.parseInt(config.getConfigProperty("database.rows_before_commit"));
			int rowsSelect = Integer.parseInt(config.getConfigProperty("database.rows_select"));
			
			String selectOrig = sqlGenerator.generateCtlSelect(owner, table, ctlOwner, ctlTable, rowsSelect, db.getConnOrig());
			String updateOrigCtl = sqlGenerator.generateCtlUpdate(ctlOwner, ctlTable);
		
			VltDAO dao = new VltDAO();
			dao.incrementalLoad(db.getConnOrig(), db.getConnDest(), selectOrig, updateOrigCtl, insertDest, deleteDest, pk, columns, rowsBeforeCommit, 0);
		
		}finally{
			try {
				db.disconnectOrig();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
